package com.example.analysis.utils;


import com.example.analysis.entity.MessageInfo;
import com.example.analysis.entity.MessageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * excel文件的工具类
 * 有几类excel文件
 * 学生成绩
 *  评教数据
 *  竞赛信息
 */

public class ExcelUtils {
    //总行数
    private static int totalRows = 0;
    //总条数
    private static int totalCells = 0;
    //错误信息接收器
    private static String errorMsg;

    //预编译
    private static final Pattern TEACHER_PATTERN = Pattern.compile("^(.*?)\\[(\\d+)\\]$");
    //分数转换
    private static final Map<String, Double> SCORE_MAPPING = new HashMap<>();
    static {
        SCORE_MAPPING.put("优", 90.0);
        SCORE_MAPPING.put("良", 80.0);
        SCORE_MAPPING.put("中", 70.0);
        SCORE_MAPPING.put("合格", 60.0);
        SCORE_MAPPING.put("及格", 60.0);
        SCORE_MAPPING.put("不及格", 59.0);
        SCORE_MAPPING.put("不合格", 59.0);
    }

    public static List<MessageInfo> getExcelInfo(MultipartFile mFile){
        String fileName = mFile.getOriginalFilename(); //获取文件名
        try {
            if (!validateExcel(fileName)) {// 验证文件名是否合格
                return null;
            }
            boolean isExcel2003 = true;// 根据文件名判断文件是2003版本还是2007版本
            if (isExcel2007(fileName)) {
                isExcel2003 = false;
            }
            List<MessageInfo>  MessageInfoList = createExcel(mFile.getInputStream(), isExcel2003);
            return MessageInfoList;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 不同的excel版本
     * @param is 输入流
     * @param isExcel2003 excel是2003还是2007版本
     * @return
     * @throws IOException
     */
    public static List<MessageInfo> createExcel(InputStream is, boolean isExcel2003) {
        try{
            Workbook wb = null;
            List<MessageInfo> MessageInfoList=new ArrayList<>();
            if (isExcel2003) {// 当excel是2003时,创建excel2003
//                wb = new HSSFWorkbook(is);
//                MessageInfoList = readExcelValue(wb);
            } else {// 当excel是2007时,创建excel2007
                wb = new XSSFWorkbook(is);
                SXSSFWorkbook swb = new SXSSFWorkbook((XSSFWorkbook)wb,100);
                MessageInfoList = readExcelValue(swb);// 读取Excel里面客户的信息
            }
            return MessageInfoList;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 读取Excel文件
     */
    public static List<MessageInfo> readExcelValue(SXSSFWorkbook swb) {
        // 得到第一个shell
        XSSFWorkbook wb=swb.getXSSFWorkbook();
        Sheet sheet = wb.getSheetAt(0);
        // 得到Excel的行数
        totalRows = sheet.getPhysicalNumberOfRows();
        List<MessageInfo> messageInfoList = new ArrayList<MessageInfo>();

        // 预处理标题行（第2行，索引2）
        Row headerRow=sheet.getRow(2);
        Map<Integer, String> columnHeaderMap = new HashMap<>();
        for (int c = 0; c < headerRow.getLastCellNum(); c++) {
            Cell headerCell = headerRow.getCell(c);
            if (headerCell != null) {
                columnHeaderMap.put(c, headerCell.getStringCellValue());
            }
        }
        DataFormatter dataFormatter = new DataFormatter();
        // 循环Excel行数  第二行是表头
        for (int r = 3; r < totalRows - 1; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            MessageInfo messageInfo = new MessageInfo();
            // 循环Excel的列
            for (int c = 0; c < columnHeaderMap.size(); c++) {
                String header = columnHeaderMap.get(c);
                if (header == null) continue;
                Cell cell = row.getCell(c);
                String cellValue = dataFormatter.formatCellValue(cell);
                switch (header) {
                    case "通知单编号":
                        messageInfo.setId(cellValue);
                        break;
                    case "学号":
                        messageInfo.setStud_id(cellValue);
                        break;
                    case "姓名":
                        messageInfo.setStud_name(cellValue);
                        break;
                    case "班级名称":
                        messageInfo.setClas(cellValue);
                        break;
                    case "课程编号":
                        messageInfo.setCourse_id(cellValue);
                        break;
                    case "课程名称":
                        messageInfo.setCourse_name(cellValue);
                        break;
                    case "开课学期":
                        messageInfo.setSemester(cellValue);
                        break;
                    case "总成绩":
                        Double score = SCORE_MAPPING.get(cellValue);
                        if (score != null) {
                            messageInfo.setScore(score);
                        } else {
                            try {
                                messageInfo.setScore(Double.parseDouble(cellValue));
                            } catch (NumberFormatException ignored) {
                                // 处理无效数值
                            }
                        }
                        break;
                    case "课程属性":
                        messageInfo.setCour_att(cellValue);
                        break;
                    case "学时":
                        messageInfo.setSub_time(cellValue);
                        break;
                    case "学分":
                        if (cell != null && cell.getCellType() == CellType.NUMERIC) {
                            messageInfo.setSub_sore(cell.getNumericCellValue());
                        } else {
                            try {
                                messageInfo.setSub_sore(Double.parseDouble(cellValue));
                            } catch (NumberFormatException ignored) {}
                        }
                        break;
                    case "录入人":
                        Matcher matcher = TEACHER_PATTERN.matcher(cellValue);
                        if (matcher.find()) {
                            messageInfo.setTeacherName(matcher.group(1));
                            messageInfo.setTeacherId(matcher.group(2));
                        }
                        break;
                }
            }
            messageInfoList.add(messageInfo);
        }
        return messageInfoList;
    }


    public static boolean validateExcel(String filePath) {
        if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
            errorMsg = "文件名不是excel格式";
            return false;
        }
        return true;
    }
    // @描述：是否是2003的excel，返回true是2003
    public static boolean isExcel2003(String filePath)  {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }
    //@描述：是否是2007的excel，返回true是2007
    public static boolean isExcel2007(String filePath)  {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }

}
